import React, { useState, useEffect, useRef } from 'react';
import styles from "./index.css";
import AMapLoader from '@amap/amap-jsapi-loader';
import FormItem from "antd/es/form/FormItem";
import FormItemInput from "antd/es/form/FormItemInput";
import {Input} from "antd";

// key:"ae01b23c39bca1f03c60e056c6293a5e",
// window._AMapSecurityConfig = {
//   securityJsCode: "d3fc5870dd254e13ed666d0fdde51c6a",
// };
const MapComponent = (props) => {
  const [map, setMap] = useState(null);
  const [searchInput, setSearchInput] = useState();
  const [searchResult, setSearchResult] = useState(null);
  console.log("pros",props)
  if (props.latitude && props.longitude && map) {
    let longitudelatitude = [props.longitude, props.latitude];
    map.setCenter(longitudelatitude); // 经度, 纬度

  }
  if (props.companyLocation && !searchInput){
    setSearchInput(props.companyLocation)

  }

  console.log(searchInput)
  useEffect(() => {

    window._AMapSecurityConfig = { securityJsCode: "d3fc5870dd254e13ed666d0fdde51c6a" };
    AMapLoader.load({
      key: "ae01b23c39bca1f03c60e056c6293a5e",
      version: "2.0",
      plugins: ["AMap.AutoComplete", "AMap.PlaceSearch",'AMap.ToolBar']
    }).then((AMap) => {
      const amap = new AMap.Map('mapContainer', {
        zoom: 11,
        center: [114.029506, 22.604214],
      });
      setMap(amap);

      const auto = new AMap.Autocomplete({
        input: "searchInput"
      });

      const placeSearch = new AMap.PlaceSearch({ map: amap });
      // 添加工具栏
      amap.addControl(new AMap.ToolBar());
      // 添加点击事件处理程序
      amap.on('click', handleMapClick);

      auto.on("select", function(e) {
        setSearchInput(e.poi.name);
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name);
      });

      placeSearch.on('searchcomplete', (status, result) => {
        if (status === 'complete') {
          setSearchResult(result);
          amap.setZoomAndCenter(result.poiList[0].location.lng, result.poiList[0].location.lat, 15);
        }
      });


      // 获取点击位置的经纬度
      function handleMapClick(e) {
        const lnglat = e.lnglat;
        // 使用Geocoder插件获取经纬度对应的地址描述
        AMap.plugin(['AMap.Geocoder'], () => {
          const geocoder = new AMap.Geocoder();

          geocoder.getAddress(lnglat, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              const address = result.regeocode.formattedAddress;
              showInfoWindow(lnglat, address);
            }
          });
        });
      }
      function showInfoWindow(lnglat, address) {
        // 创建信息窗口实例
        setSearchInput(address)
        let  newCompany = props.company;

        newCompany.companyLocation = address;
        newCompany.latitude = lnglat.lat;
        newCompany.longitude = lnglat.lng;
        props.setCompany(newCompany);
        // <a style="font-size:18px;position:absolute;top:0px;right:12px;cursor: pointer;border: 0; background: #fff;"  href="javascript:getLngLat()">x</a>
        const infoWindow = new AMap.InfoWindow({
          // isCustom: true,
          content: `
                <div style="padding: 10px; background: #fff; border-radius: 5px;position: relative;">

                    <h3>当前位置</h3>
                    <p>${address}</p>
                </div>
            `,
          offset: new AMap.Pixel(0, -30),
          closeWhenClickMap: true
        });

        // 打开信息窗口
        infoWindow.open(amap, lnglat);
        function getLngLat() {
          // 在这里可以添加按钮点击后的逻辑
          infoWindow.close();
        }
      }



      // 清除事件监听
      return () => {
        amap.clearEvents();
      };
    })


    function handleButtonClick(e) {
      // 在这里可以添加按钮点击后的逻辑
      console.log('Button clicked');
    }



    return () => {
      if (map) {
        map.destroy();
      }
    };
  }, []);




  return (
    <div>
      <Input
        id="searchInput"
        type="text"
        style={{width: '300%'}}
        width={"400px"}
        value={searchInput}
        defaultValue={props.companyLocation}
        onChange={(e) => setSearchInput(e.target.value)}
      />
      <div id="mapContainer" style={{ width: '300%', height: '400px' }}></div>
    </div>
  );
};

/**
 class  MapComponent extends Component{
 constructor(){
 super();
 this.map = null;
 }
 // 2.dom渲染成功后进行map对象的创建
 componentDidMount(){
 window._AMapSecurityConfig = {
 securityJsCode: "d3fc5870dd254e13ed666d0fdde51c6a",
 };
 AMapLoader.load({
 key:"ae01b23c39bca1f03c60e056c6293a5e",                     // 申请好的Web端开发者Key，首次调用 load 时必填
 version:"2.0",              // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
 plugins:["AMap.Scale", "AMap.ToolBar", "AMap.HawkEye",
 "AMap.Geolocation", "AMap.PlaceSearch", "AMap.Geocoder"],     //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
 }).then((AMap)=>{

 this.map = new AMap.Map("container",{ //设置地图容器id
 viewMode:"3D",         //是否为3D地图模式
 zoom:11,                //初始化地图级别
 center:[105.602725,37.076636], //初始化地图中心点位置
 });
 var toolbar = new AMap.ToolBar(); //创建工具条插件实例
 // this.map.addControl(toolbar); //添加工具条插件到页面


 }).catch(e=>{
 console.log(e);
 })


 }
 render(){
 // 1.初始化创建地图容器,div标签作为地图容器，同时为该div指定id属性；
 return (
 <div>
 <div id="my-panel"></div>
 <div id="container" className={styles.container} style={{ height: '300px', width:"300px"}} >
 </div>
 </div>
 );
 }
 }
 */
//导出地图组建类
export default MapComponent;
